package org.redis.cluster.registry.zookeeper;

import java.util.Collection;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.redis.cluster.registry.Listener;
import org.redis.cluster.registry.exception.RegistryException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ZookeeperRegistryWatcher {
	
	protected final Logger logger=LoggerFactory.getLogger(getClass());
	
	private final ConcurrentHashMap<String,PathChildrenCache> watcherCache=new ConcurrentHashMap<String,PathChildrenCache>();
	private final ConcurrentHashMap<String,Collection<Listener>> listenerCache=new ConcurrentHashMap<String,Collection<Listener>>();
	
	private CuratorFramework client;
	
	public ZookeeperRegistryWatcher(CuratorFramework client) {
		this.client=client;
	}
	
	public boolean listen(String path,Listener listener) {
		if(logger.isDebugEnabled()) {
			logger.debug("准备监听 - {}", path);
		}
		
		PathChildrenCache pathChildrenCache=watcherCache.get(path);
		if(pathChildrenCache!=null) {
			listenerCache.get(path).add(listener);
			return true;
		}
		
		pathChildrenCache=new PathChildrenCache(client,path,false);
		listenerCache.putIfAbsent(path, new CopyOnWriteArrayList<Listener>());
		if(watcherCache.putIfAbsent(path, pathChildrenCache)!=null) {
			return listen(path,listener);
		}
		
		listenerCache.get(path).add(listener);
		
		pathChildrenCache.getListenable().addListener((CuratorFramework client, PathChildrenCacheEvent event)->{
			if(logger.isDebugEnabled()) {
				logger.debug("收到监听 - {}",event);
			}
			
			for(Listener tempListener:listenerCache.get(path)) {
				tempListener.onListen(path);
			}
		});
		
		try {
			pathChildrenCache.start();
			return true;
		}
		catch(Exception e) {
			throw new RegistryException(e);
		}
	}

	public boolean unlisten(String path,Listener listener) {
		if(logger.isDebugEnabled()) {
			logger.debug("取消监听 - {}", path);
		}
		
		Collection<Listener> listeners=listenerCache.get(path);
		if(CollectionUtils.isEmpty(listeners)) {
			return false;
		}
		
		listeners.remove(listener);
		return true;
	}
	
	public void destroy() {
		if(MapUtils.isEmpty(watcherCache)) {
			return;
		}
		
		for(Entry<String,PathChildrenCache> entry:watcherCache.entrySet()) {
			if(logger.isDebugEnabled()) {
				logger.debug("关闭watcher - {}",entry.getKey());
			}
			
			try {
				entry.getValue().close();
			}
			catch(Exception e) {
				throw new RegistryException(e);
			}
		}
	}
}